package com.health.fragment.person;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.bumptech.glide.Glide;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.PersonalFileActivity;
import com.health.viewscontrols.PersonalFileActivity.onFragmentSave;
import com.health.R;
import com.health.db.DbManager;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.HD_PERSONAL_HEALTH_PHOTO;
import com.health.tools.GlobalConts;
import com.health.tools.SPUtil;
import com.health.viewscontrols.tjbg.CameraActivity;
import com.health.widget.EditTextWithDate;
import com.nova.tools.ImageUtil;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

/**
 * 封面信息
 * 
 * @author nova
 *
 */
public class CoverFragment extends com.nova.BaseFragment implements OnClickListener, onFragmentSave {
	private View view;
	private EditText nameEt;
	/**
	 * 建档单位
	 */
	private EditText departmentEt;
	/**
	 * 现住址
	 */
	private EditText addrEt;
	/**
	 * 建档人
	 */
	private EditText jiandangrenEt;
	/**
	 * 户籍地址
	 */
	private EditText hujiAddrEt;

	/**
	 * 责任医生
	 */
	private EditText doctorEt;
	/**
	 * 联系电话
	 */
	private EditText phoneEt;
	/**
	 * 建档日期
	 */
	private EditTextWithDate dateEt;
	/**
	 * 乡镇（街道）
	 */
	private EditText townEt;
	/**
	 * 村（居委会）
	 */
	private EditText villageEt;
	private NovaApplication app;
	private ImageView photoImgView;
	ARCHIVE_BASEINFO userInfo = null;
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

	private final int REQUEST_CODE_PHOTO = 0x1005;
	private Button bt_paizhaop;
	private ImageView iv_paizhaop_img;
	private String mPhotoPath;

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.cover, container, false);
		return view;
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		initView();
		setData();

	}

	private void initView() {
		nameEt = (EditText) view.findViewById(R.id.cover_name_edit);
		departmentEt = (EditText) view.findViewById(R.id.cover_department_edit);
		addrEt = (EditText) view.findViewById(R.id.cover_address_edit);
		jiandangrenEt = (EditText) view.findViewById(R.id.cover_jiandangren_edit);
		hujiAddrEt = (EditText) view.findViewById(R.id.cover_hujiaddress_edit);
		doctorEt = (EditText) view.findViewById(R.id.cover_doctor_edit);
		phoneEt = (EditText) view.findViewById(R.id.cover_phone_edit);
		dateEt = (EditTextWithDate) view.findViewById(R.id.cover_date_edit);

		townEt = (EditText) view.findViewById(R.id.cover_street_edit);
		villageEt = (EditText) view.findViewById(R.id.cover_village_edit);
		photoImgView = (ImageView) view.findViewById(R.id.cover_img);
		bt_paizhaop = (Button) view.findViewById(R.id.bt_paizhaop);
		iv_paizhaop_img = (ImageView) view.findViewById(R.id.iv_paizhaop_img);
		// GlobalConts.setMaxLength(100, nameEt);
		// GlobalConts.setMaxLength(10, departmentEt);//
		GlobalConts.setMaxLength(250, addrEt);
		// GlobalConts.setMaxLength(20, jiandangrenEt);
		GlobalConts.setMaxLength(250, hujiAddrEt);
		GlobalConts.setMaxLength(25, doctorEt);
		GlobalConts.setMaxLength(20, phoneEt);
		GlobalConts.setMaxLength(10, dateEt);
		// GlobalConts.setMaxLength(10, townEt);// 乡镇（街道）
		// GlobalConts.setMaxLength(13, villageEt);// 村（居委会）
		dateEt.setBefore(new Date());
		bt_paizhaop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(getActivity(), CameraActivity.class), REQUEST_CODE_PHOTO);
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == REQUEST_CODE_PHOTO) {
				String path = data.getStringExtra("result"); // 图片地址
				Glide.with(getActivity()).load(path).into(iv_paizhaop_img);
				mPhotoPath = path;
			}
		}
	}

	private void setData() {
		userInfo = NovaApplication.getUserInfo();
		nameEt.setText(userInfo.getCUSTOMERNAME());
		String str_name = SPUtil.getstr_jdr(getActivity());
		jiandangrenEt.setText(str_name);
		departmentEt.setText(userInfo.getCREATEUNIT_NAME());
		hujiAddrEt.setText(userInfo.getHOUSEHOLD_ADDR());
		addrEt.setText(userInfo.getADDR());
		doctorEt.setText(str_name);
		doctorEt.setFocusable(false);
		townEt.setText(userInfo.getTOWNNAME());
		villageEt.setText(userInfo.getVILLAGENAME());
		phoneEt.setText(userInfo.getPHONE());
		String createDate = userInfo.getCREATED_DATE();
		createDate = createDate == null ? new Date(System.currentTimeMillis()).toString() : createDate;
//		String date = format.format(createDate);
		dateEt.setText(createDate);

		if (!TextUtils.isEmpty(userInfo.getRES4())) {
			Glide.with(getActivity()).load(userInfo.getRES4()).into(iv_paizhaop_img);
		}

		DbManager dbmanger = ((NovaApplication) getActivity().getApplication()).getDbManger();
		List<HD_PERSONAL_HEALTH_PHOTO> queses = dbmanger.selectDataPHOTO(userInfo.getIDCARD());
		if (queses.size() > 0) {
			HD_PERSONAL_HEALTH_PHOTO ques = queses.get(0);
			if (ques.getPHOTO() != null) {
				Log.w("dddddddddddd", Arrays.toString(ques.getPHOTO()));
				byte[] sz_photo = ques.getPHOTO();
				if (sz_photo != null) {
					// getImgFromArray();
					Bitmap bitmap = BitmapFactory.decodeByteArray(sz_photo, 0, sz_photo.length);
					if (GlobalConts.photo_flag.equals("circle")) {
						getImgFromPath();
						photoImgView.setImageBitmap(ImageUtil.toRoundBitmap(bitmap));
					} else {
						photoImgView.setImageBitmap(bitmap);
					}
				}
			}
		}
	}

	public void save() {
		if (TextUtils.isEmpty(phoneEt.getText().toString())) {
			((PersonalFileActivity) getActivity()).showTextDialog("请输入联系电话");
			return;
		}
		ARCHIVE_BASEINFO userInfo = NovaApplication.getUserInfo();
		if (GlobalConts.isPhoneNumberValid(phoneEt.getText().toString())) {
			userInfo.setPHONE(phoneEt.getText().toString());
		} else {
			((PersonalFileActivity) getActivity()).showTextDialog("联系电话不正确");
			return;
		}
		String str_date = dateEt.getText().toString();
		if (TextUtils.isEmpty(str_date)) {
			((PersonalFileActivity) getActivity()).showTextDialog("请选择建档日期");
			return;
		}
		userInfo.setCREATED_DATE(str_date);
		try {
			userInfo.setLAST_UPDATE_DATE(
					GlobalConts.datetimeFormat.parse(GlobalConts.datetimeFormat.format(new Date())));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// userInfo.setDOCTOR(doctorEt.getText().toString());
		userInfo.setADDR(addrEt.getText().toString());
		userInfo.setHOUSEHOLD_ADDR(TextUtils.isEmpty(hujiAddrEt.getText().toString().trim())?"":hujiAddrEt.getText().toString().trim());

		if (!TextUtils.isEmpty(mPhotoPath)) {
			userInfo.setRES4(mPhotoPath);
		}
		userInfo.setIS_UPDATE("Y");
		NovaApplication.fdbmanger.updata(userInfo, "IDCARD LIKE '" + NovaApplication.getUserInfo().getIDCARD() + "'");
		// NovaApplication.fdbmanger.delete(NovaApplication.userInfo);

		NovaApplication.setUserInfo(userInfo);
		((PersonalFileActivity) getActivity()).showTextDialog("保存成功");
		DetailInfoFragment.setPhone(phoneEt.getText().toString());
	}
	
	@Override
	public void onClick(View v) {

	}

	@Override
	public void setTizhong(String value) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setXuetang(String value) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setXueya(String gaoya, String diya, String mailv) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setTiWen(String tiwen) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setXueHongDanBai(String xhdb) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setMaiLv(String mailv) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setLiBangECG(String libangEcgResult, String time) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setNiaoYeFenxi(String niaoDanYuan, String qianXue, String DanHongSu, String tongti, String puTaoTang,
			String danBaiZhi, String PH, String yaXiaoSuan, String baiXiBao, String biZhong, String weiShengSu) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setCHOL(String dgc) {

	}

	/**
	 * 从数据库二进制获取图片
	 * 
	 * @author 王婷婷
	 * @date 2017年3月24日 上午11:59:30
	 */
	private void getImgFromArray() {
		DbManager dbmanger = ((NovaApplication) getActivity().getApplication()).getDbManger();
		List<HD_PERSONAL_HEALTH_PHOTO> queses = dbmanger.selectDataPHOTO(userInfo.getIDCARD());
		if (queses.size() > 0) {
			HD_PERSONAL_HEALTH_PHOTO ques = queses.get(0);
			if (ques.getPHOTO() != null) {
				Log.w("dddddddddddd", Arrays.toString(ques.getPHOTO()));
				byte[] sz_photo = ques.getPHOTO();
				if (sz_photo != null) {

					Bitmap bitmap = BitmapFactory.decodeByteArray(sz_photo, 0, sz_photo.length);
					if (GlobalConts.photo_flag.equals("circle")) {

						photoImgView.setImageBitmap(ImageUtil.toRoundBitmap(bitmap));
					} else {
						photoImgView.setImageBitmap(bitmap);
					}
				}
			}
		}
	}

	/**
	 * 从数据库地址获取图片
	 * 
	 * @author 王婷婷
	 * @date 2017年3月24日 上午11:59:30
	 */
	private void getImgFromPath() {
		List<HD_PERSONAL_HEALTH_PHOTO> queses = NovaApplication.fdbmanger.findAllByWhere(HD_PERSONAL_HEALTH_PHOTO.class,
				"CARDID='" + userInfo.getIDCARD() + "'");
		if (queses.size() > 0) {
			HD_PERSONAL_HEALTH_PHOTO ques = queses.get(0);
			if (!TextUtils.isEmpty(ques.getRES0())) {
				Bitmap bitmap = ImageUtil.convertToBitmap(ques.getRES0(), 600, 600);
				if (GlobalConts.photo_flag.equals("circle")) {

					photoImgView.setImageBitmap(ImageUtil.toRoundBitmap(bitmap));
				} else {
					photoImgView.setImageBitmap(bitmap);
				}

			}

		}

	}

	@Override
	public void setXinLv(String xinlv) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setXueYang(String xueYang) {

	}

}
